package ru.ifmo.itmokis.sim;

import java.util.List;
import org.apache.log4j.Logger;
import ru.ifmo.itmokis.Facade;
import ru.ifmo.itmokis.domain.Supply;
import ru.ifmo.itmokis.domain.Time;
import ru.ifmo.itmokis.util.DataContext;
import ru.ifmo.itmokis.util.EventDriven;

/**
 *
 * @author Ivan Stepuk
 */
public class DeliveryFactory implements ClockListener, EventDriven {

    private Facade facade;
    private DataContext dataContext;
    // ^ Dependencies ^
    private Time nextEventTime = Time.ZERO;

    public DeliveryFactory(Facade facade, DataContext dataContext) {
        this.facade = facade;
        this.dataContext = dataContext;
    }

    @Override
    public void process(Time time) {
        if (time.equals(nextEventTime)) {
            Logger.getLogger(getClass()).debug(time + ": delivery income");
            List<Supply> undelivered = dataContext.getUndeliveredSupplies();
            for (Supply s : undelivered) {
                dataContext.updateSupplyDeliveryTime(s, time);
                facade.deliverNewMaterials(s);
            }
        }
    }

    @Override
    public void scheduleEvent(Time time) {
        nextEventTime = time;
    }
}
